package com.siemens.industrial.web.mvc.dao.admin;

import com.siemens.industrial.model.admin.Tenant;
import com.siemens.industrial.model.admin.User;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Types;
import java.util.List;
import java.util.Map;

/**
 * Created by qupen on 2016/8/31.
 */
@Service
public class UserDao {
    @Resource
    JdbcTemplate jdbcTemplate;

    private static final String getUserCountQuery = "SELECT COUNT(1) FROM `siemens`.`user` WHERE `enabled` = 1";
    private static final String getMessageCountQuery = "SELECT count(1) FROM siemens.message where user_id = ? and status=0;";
    private static final String getUserListQuery = "SELECT * FROM `siemens`.`user` WHERE `enabled`<>-1";
    private static final String getOneByIdQuery = "SELECT * FROM `siemens`.`user` WHERE `user_id`=?";
    private static final String addUserQuery = "INSERT INTO `siemens`.`user` (`user_id`,`user_name`,`user_pwd`,`enabled`,`role_id`,`telephone`,`logo_md5`,`department`,`dashboard_config`,`email`) VALUES (?,?,?,?,?,?,?,?,?,?)";
    private static final String updateUserQuery = "UPDATE `siemens`.`user` SET user_name=?,role_id=?,user_pwd=?,enabled=?,telephone=?,logo_md5=?,department=?,dashboard_config=?,email=? WHERE user_id=?";
    private static final String updateUserEnableQuery = "UPDATE `siemens`.`user` SET `enabled`=? WHERE `user_id`=?;";
    private static final String initUserPasswordQuery = "UPDATE `siemens`.`user` SET `user_pwd`=? WHERE `user_id`=?;";
    private static final String findOneByUserNameQuery = "SELECT * FROM `siemens`.`user` WHERE `user_name`=?;";
    private static final String findOneByTenantNameQuery = "SELECT * FROM `siemens`.`tenant` WHERE `tenant_name`=?;";
    private static final String getAllMessageByUserId="select * from siemens.message order by create_time desc;";
    private static final String updateMessageStatus="UPDATE siemens.message SET status = 1 WHERE user_id = ?;";
    public int getUserCount() {
        return jdbcTemplate.queryForObject(getUserCountQuery, Integer.class);
    }

    private static final String findAllLikeExecutant = "SELECT DISTINCT `executant` FROM `siemens`.`message` WHERE `executant` LIKE ?";
    private static final String findAllLikeOperands = "SELECT DISTINCT `operands` FROM `siemens`.`message` WHERE `operands` LIKE ?";

    /**
     * 平台管理员列表
     *
     * @return user List
     */
    public List<User> getUsers() {
        return jdbcTemplate.query(getUserListQuery, User.getRowMapper());
    }

    /**
     * 根据userId 查找到一个管理员
     *
     * @param userId
     * @return
     */
    public List<User> findOneById(String userId) {
        return jdbcTemplate.query(getOneByIdQuery, new Object[]{userId}, User.getRowMapper());
    }

    /**
     * 更新管理员信息
     *
     * @param user
     * @return
     */
    public int updateUser(User user) {
        return jdbcTemplate.update(updateUserQuery, pss -> {
            pss.setString(1, user.getUserName());
            pss.setInt(2, user.getRoleId());
            pss.setString(3, user.getPassword());
            pss.setInt(4, user.getEnabled());
            pss.setString(5, user.getTelephone());
            pss.setString(6, user.getLogoMd5());
            pss.setString(7, user.getDepartment());
            pss.setString(8, user.getDashboardConfig());
            pss.setString(9, user.getEmail());
            pss.setString(10, user.getUserId());
        });
    }

    /**
     * 创建新的管理员
     *
     * @param user
     */
    public void save(User user) {
        jdbcTemplate.update(addUserQuery, pss -> {
                    pss.setString(1, user.getUserId());
                    pss.setString(2, user.getUserName());
                    pss.setString(3, user.getPassword());
                    pss.setInt(4, user.getEnabled());
                    pss.setInt(5, user.getRoleId());
                    pss.setString(6, user.getTelephone());
                    pss.setString(7, user.getLogoMd5());
                    pss.setString(8, user.getDepartment());
                    pss.setString(9, user.getDashboardConfig());
                    pss.setString(10, user.getEmail());
                }
        );
    }

    /**
     * 禁用 启用
     *
     * @param userId
     * @param enabled
     * @return
     */
    public int updateEnabled(String userId, int enabled) {
        return jdbcTemplate.update(updateUserEnableQuery, enabled, userId);
    }

    /**
     * 重置密码
     *
     * @param userId
     * @param password
     * @return
     */
    public int initPassword(String password, String userId) {
        return jdbcTemplate.update(initUserPasswordQuery, password, userId);
    }

    /**
     * 根据用户名查找用户
     *
     * @param userName
     * @return
     */
    public User findOneByName(String userName) {
        try {
            return jdbcTemplate.queryForObject(findOneByUserNameQuery, new Object[]{userName}, new int[]{Types.VARCHAR}, User.getRowMapper());
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    /**
     * 根据租户名查找用户名
     *
     * @param tenantName
     * @return
     */
    public Tenant findTenantByName(String tenantName) {
        try {
            return jdbcTemplate.queryForObject(findOneByTenantNameQuery, new Object[]{tenantName}, new int[]{Types.VARCHAR}, Tenant.getRowMapper());
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    public int getMessCount(String userId) {
        return jdbcTemplate.queryForObject(getMessageCountQuery,new Object[]{userId},Integer.class);
    }

    public List<Map<String,Object>> getAllMessage(String sql){
        return jdbcTemplate.queryForList(sql);
    }

    public void updateStatusForMessage(String userId){
        jdbcTemplate.update(updateMessageStatus,userId);
    }

    public List<Map<String,Object>> findAllLikeExecutant(String str){
        return jdbcTemplate.queryForList(findAllLikeExecutant,String.format("%%%s%%", str));
    }
    public List<Map<String,Object>> findAllLikeOperands(String str){
        return jdbcTemplate.queryForList(findAllLikeOperands,String.format("%%%s%%", str));
    }
}
